/**
 * Copyright 2009-2011 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.myjung.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.myjung.Myjung;

/**
 * @author Steve M. Jung
 */
public class ListMap<K, V> extends HashMap<K, V> {
	private static final long serialVersionUID = 1L;
	private List<K> keyList = new ArrayList<K>();
	private List<V> valueList = new ArrayList<V>();

	public ListMap() {
		super();
	}
	public ListMap(int size) {
		super(size);
	}
	public ListMap(int size, float arg1) {
		super(size, arg1);
	}
	public ListMap(Map<K, V> map) {
		super(map);
		this.putList(map, -1);
	}

	@Override
	public V put(K key, V value) {
		if (value == null) {
			remove(key);
			return null;
		}
		this.putList(key, value, -1);
		return super.put(key, value);
	}
	@Override
	public void putAll(Map<? extends K, ? extends V> map) {
		putAll(map, -1);
	}
	public void putAll(Map<? extends K, ? extends V> map, int index) {
		if (Myjung.isEmpty(map))
			return;
		this.putList(map, index);
		for (K key : map.keySet())
			super.put(key, map.get(key));
	}
	@Override
	public V remove(Object key) {
		removeList(key);
		return super.remove(key);
	}
	public Collection<K> keys() {
		return keyList;
	}
	public Collection<V> values() {
		return valueList;
	}
	public List<K> keyList() {
		return keyList;
	}
	public List<V> valueList() {
		return valueList;
	}

	private void putList(Map<? extends K, ? extends V> map, int index) {
		@SuppressWarnings("unchecked")
		Collection<K> keys = map instanceof ListMap<?, ?> ? ((ListMap<K, V>) map).keys() : (Collection<K>) map.keySet();
		for (K key : keys)
			putList(key, map.get(key), index++);
	}

	private void putList(K key, V value, int index) {
		if (key == null)
			return;
		removeList(key);
		if (index < 0) {
			keyList.add(key);
			valueList.add(value);
		} else {
			keyList.add(index, key);
			valueList.add(index, value);
		}
	}
	private void removeList(Object key) {
		if (!keyList.contains(key))
			return;
		int index = keyList.indexOf(key);
		keyList.remove(index);
		valueList.remove(index);
	}
	public void clear() {
		super.clear();
		keyList.clear();
		valueList.clear();
	}

}